package com.coin.exchanges.view.fragment.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.coin.exchanges.R;
import com.coin.exchanges.adapter.NewMarketAdapter;
import com.coin.exchanges.aop.CheckLogin;
import com.coin.exchanges.config.FragmentConfig;
import com.coin.exchanges.model.MarketBean;
import com.coin.exchanges.model.okex.response.FuturesInstrumentsTickerList;
import com.coin.exchanges.model.okex.vo.HotCoinItemVO;
import com.coin.exchanges.model.okex.vo.RankItemVO;
import com.coin.exchanges.mvp.KLine.KLineActivity;
import com.coin.exchanges.net.RetrofitFactory;
import com.coin.exchanges.presenter.MarketPresenter;
import com.coin.exchanges.utils.AppUtils;
import com.coin.exchanges.utils.IconInfoUtils;
import com.coin.exchanges.utils.OkExSettlementComparator;
import com.coin.exchanges.utils.SpUtils;
import com.coin.exchanges.view.MainActivity;
import com.coin.exchanges.view.user.bean.UserLoginBean;
import com.coin.libbase.net.rxjava.RxObservableSubscriber;
import com.coin.libbase.utils.DoubleUtils;
import com.coin.libbase.view.fragment.JBaseFragment;
import com.flyco.tablayout.SlidingTabLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.bgabanner.BGALocalImageSize;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class NewMarketFragment extends JBaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.banner)
    BGABanner mBanner;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRereshLayout;
    private NewMarketAdapter mAdapter;

    public static Fragment newInstance() {
        return new NewMarketFragment();
    }

    @Override
    protected View onCreateFragmentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_new_market, container, false);
    }

    @Override
    protected void initView(View view) {

        initBanner();
        initAdapter();
        initData();
    }

    //https://easydoc.xyz/#/s/83192239
    private void initData() {
        RetrofitFactory
                .getOkExApiService()
                .getTicker()
                .subscribeOn(Schedulers.io())
                .map(new Function<List<FuturesInstrumentsTickerList>, List<RankItemVO>>() {
                    @Override
                    public List<RankItemVO> apply(List<FuturesInstrumentsTickerList> tickerList) throws Exception {

                        OkExSettlementComparator comparator = new OkExSettlementComparator();

                        // 归组
                        Map<String, List<FuturesInstrumentsTickerList>> map = new HashMap<>();
                        for (FuturesInstrumentsTickerList insItem : tickerList) {
                            String rootName = IconInfoUtils.getRootName(insItem.getInstrument_id());
                            List<FuturesInstrumentsTickerList> list;
                            if (map.containsKey(rootName)) {
                                list = map.get(rootName);
                            } else {
                                list = new ArrayList<>(3);
                                map.put(rootName, list);
                            }

                            insItem.setDayTime(IconInfoUtils.getDayTime(insItem.getInstrument_id()));
                            list.add(insItem);
                        }

                        List<FuturesInstrumentsTickerList> resultList = new ArrayList<>(24);
                        for (Map.Entry<String, List<FuturesInstrumentsTickerList>> entry : map.entrySet()) {
                            List<FuturesInstrumentsTickerList> list = entry.getValue();
                            // 进行每项排序
                            Collections.sort(entry.getValue(), comparator);

                            // 进行赋值
                            String[] useDisArray;
                            int listSize = list.size();
                            switch (listSize) {
                                case 1:
                                    useDisArray = ONE;
                                    break;
                                case 2:
                                    useDisArray = TWO;
                                    break;
                                case 3:
                                    useDisArray = THREE;
                                    break;
                                default:
                                    useDisArray = THREE;
                                    break;
                            }
                            for (int i = 0; i < listSize; ++i) {
                                FuturesInstrumentsTickerList curItem = list.get(i);
                                String nameDes = IconInfoUtils.getDesName(curItem.getInstrument_id());
                                nameDes = TextUtils.isEmpty(nameDes) ? "" : "-" + nameDes;
                                if (i < 3) {
                                    curItem.setDisplayName(useDisArray[i] + nameDes);
                                } else {
                                    curItem.setDisplayName(useDisArray[2] + nameDes);
                                }
                            }

                            resultList.addAll(list);
                        }

                        // 进行数据转换
                        List<RankItemVO> rankItemVOList = new ArrayList<>();
                        for (int i = 0; i < resultList.size(); ++i) {
                            FuturesInstrumentsTickerList item = resultList.get(i);

                            String instrumentId = item.getInstrument_id();

                            RankItemVO rankItemVO = new RankItemVO();
                            // 排行榜 名次
                            rankItemVO.setNum(i + 1);
                            // 名称
                            rankItemVO.setName(IconInfoUtils.getRootName(instrumentId));
                            // 当季、当周、次周
                            rankItemVO.setNameDes(item.getDisplayName());
                            // 最新价
                            rankItemVO.setValue(item.getLast() + "");
                            // 交易量
                            rankItemVO.setVolume(getFormatVolume(item.getVolume_24h()));
                            // 设置当前市价
//                            rankItemVO.setCurLast(item.getLast());

                            rankItemVO.setInsId(instrumentId);

                            double mean = (item.getHigh_24h() + item.getLow_24h()) / 2;
                            double range = (item.getLast() - mean) / mean;

                            rankItemVO.setRange(DoubleUtils.formatTwoDecimal(range * 100));
                            rankItemVO.setIncrease(range >= 0);

                            rankItemVOList.add(rankItemVO);

                        }

                        // 将结果排序
                        Collections.sort(rankItemVOList);

                        if (rankItemVOList.size() > MAX_SIZE) {
                            rankItemVOList = rankItemVOList.subList(0, MAX_SIZE);
                        }
                        for (int j = 0; j < rankItemVOList.size(); ++j) {
                            rankItemVOList.get(j).setNum(j + 1);
                        }

                        return rankItemVOList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<RankItemVO>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<RankItemVO> marketBeans) {
                        mAdapter.setNewData(marketBeans);
                        if (mSwipeRereshLayout != null)
                            mSwipeRereshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mSwipeRereshLayout != null)
                            mSwipeRereshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private static final long TEN_THOUSAND = 10000;
    private static final int MAX_SIZE = 10;

    /**
     * 格式化，过万时返回：xxxx万；未过万时返回：xxx
     *
     * @param volume
     * @return
     */
    private String getFormatVolume(long volume) {
        // 大于一万，则用万做单位
        if (volume > TEN_THOUSAND) {
            return (volume / TEN_THOUSAND) + "万";
        }
        return volume + "";
    }

    List<RankItemVO> mLists = new ArrayList<>();
    private static final String[] ONE = {"当周"};
    private static final String[] TWO = {"当周", "当季"};
    private static final String[] THREE = {"当周", "次周", "当季"};

    private void initAdapter() {
        mSwipeRereshLayout.setOnRefreshListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new NewMarketAdapter(R.layout.item_rank, mLists);
        View headView = LayoutInflater.from(getActivity()).inflate(R.layout.item_rank_title, null);
        mAdapter.setHeaderView(headView);
        mRecyclerView.setAdapter(mAdapter);
//        mSwipeRereshLayout.setRefreshing(true);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<RankItemVO> data = mAdapter.getData();
                RankItemVO item = data.get(position);
                Intent intent = new Intent();
                intent.putExtra(FragmentConfig.INSTRUMENT_ID, item.getInsId()); //KLineActivity 一样存在要一起改
                intent.putExtra(FragmentConfig.TYPE, item.getNameDes());
                intent.putExtra(FragmentConfig.FROM, AppUtils.OKEX);
                intent.setClass(getActivity(), KLineActivity.class);
                getActivity().startActivity(intent);
            }
        });
    }

    // 初始化banner
    private void initBanner() {
        BGALocalImageSize localImageSize = new BGALocalImageSize(720, 1280, 320, 640);
        mBanner.setData(localImageSize, ImageView.ScaleType.CENTER_CROP, R.mipmap.banner_one, R.mipmap.banner_two, R.mipmap.banner_three);
        mBanner.startAutoPlay();
    }

    @Override
    public void onRefresh() {
        initData();
    }
}
